//
//  PhysicSystem.m
//  TestCocosWithBox2
//
//  Created by Nguyen Tan Loc on 8/14/13.
//  Copyright (c) 2013 Nguyen Tan Loc. All rights reserved.
//

#import "PhysicSystem.h"

PhysicSystem* PhysicSystem::mInstance = NULL;

PhysicSystem::PhysicSystem()
{
    mWorld = new b2World(b2Vec2(0, 0));
    mWorld->SetAllowSleeping(false);
    mWorld->SetContinuousPhysics(false);
    
    mDebugDraw = new GLESDebugDraw(PTM_RATIO);
    mWorld->SetDebugDraw(mDebugDraw);
    
    uint32 flags = 0;
    flags += b2Draw::e_shapeBit;
    mDebugDraw->SetFlags(flags);
    
    mContactListener = new MyContactListener();
    mWorld->SetContactListener(mContactListener);
}

PhysicSystem* PhysicSystem::getInstance()
{
    if (mInstance == NULL)
    {
        mInstance = new PhysicSystem();
    }
    
    return mInstance;
}

void PhysicSystem::update(ccTime dt)
{
    mWorld->Step(dt, 8, 1);
}

void PhysicSystem::drawDebug()
{
    ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );
	
	kmGLPushMatrix();
	
    mWorld->DrawDebugData();
	
	kmGLPopMatrix();
}

void PhysicSystem::destroyAllBody()
{
    for (b2Body *body = mWorld->GetBodyList(); body; body = body->GetNext())
	{
        mWorld->DestroyBody(body);
    }
}

void PhysicSystem::dealloc()
{
    CCLOG(@"println");
}